package app.Main;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.StringTokenizer;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;

import app.frequentpatterns.fpgrowth.AlgoFPGrowth;
import app.frequentpatterns.fpgrowth.Database;
import app.frequentpatterns.fpgrowth.Itemset;
import app.frequentpatterns.fpgrowth.Itemsets;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * 
 * @author Kumori
 */
public class AppControl extends JFrame implements ActionListener {
	private JMenu fileMenu;
	/** Threshold input menu. */
	private JMenu tHoldInputMenu;
	/** Data pre-processing input menu. */
	private JMenu dataPreProcMenu;
	/** Algorithm menu. */
	private JMenu algoMenu;

	/** Output menu. */
	private JMenu outputMenu;
	/** Data array output sub-menu. */
	private JMenu dataArrayOutputMenu;

	/** Frequent set output sub-menu. */
	private JMenu freqSetOutputMenu;
	/** Association rule output sub-menu. */
	private JMenu assocRuleOutputMenu;
	/** Diagnostic output sub-menu. */
	private JMenu diagnosticOutputSubMenu;
	
	// Menu items
	/** File menu items. */
	private JMenuItem[] fileMenuItems;
	/** Threshold input menu items. */
	private JMenuItem[] tholdInputMenuItems;
	/** Data pre-processing menu items. */
	private JMenuItem[] dataPreProcMenuItems;
	/** Algorithm menu items. */
	private JMenuItem[] algoMenuItems;

	/** Output menu items. */
	private JMenuItem[] outputMenuItems;
	/** Data array output sub-menu items. */
	private JMenuItem[] dataArrayOutputMenuItems;
	/** Frequent set output sub-menu items. */
	private JMenuItem[] freqSetOutputMenuItems;
	/** Association rule output sub-menu items. */
	private JMenuItem[] assocRuleOutputMenuItems;
	/** Diagnostic output sub-menu items. */
	private JMenuItem[] diagnosticOutputMenuItems;

	// Menu labels
	/** File menu labels. */
	private String fileMenuLabels[] = { "About", "Load Data", "Load Weight","Randomize Weight",
			"Exit" };
	/** Threshold parameter input menu labels. */
	private String tHoldInputMenuLabels[] = { "Support", "Min Weight" };
	/** Data pre-processing menu labels. */
	private String dataPreProcMenuLabels[] = { "Sort", "Sort & Prune" };
	/** Algorithm menu labels. */
	private String algoMenuLabels[] = { "WFIM (Weighted frequent itemset mining)" };
	/** Ouput menu labels. */
	private String outputMenuLables[] = { "Output Schema" };
	/** Output data array sets sub-menu labels. */
	private String outputDataArrayMenuLabels[] = { "Data Att. Numbers",
			"Data Output Schema" };
	/** Output T-tree sub-menu labels. */
	private String outputTtreeMenuLabels[] = { "T-tree Statistics",
			"T-Tree (Att. Numbers)", "T-tree (Graph)" };
	/** Output T-tree sub-menu labels. */
	private String outputDIC_TtreeMenuLabels[] = { "DIC T-tree Stats",
			"DIC T-Tree (Att. Numbers)" };
	/** Output frequent sets sub-menu labels. */
	private String outputFreqSetsMenuLabels[] = { "FSs Att. Numbers",
			"FSs Output Schema" };
	/** Output ARs sub-menu labels. */
	private String outputAssocRulesMenuLabels[] = { "ARs Att. Numbers",
			"ARs Output Schema" };
	/** Diagnostic output sub-menu labels. */
	private String outputDiagnosticMenuLabels[] = { "Conversion arrays" };

	// OTHER COMPONBENTS
	/** Credits panel */
	private JPanel creditsPanel;
	/** Text Area. */
	private JTextArea textArea;
	private int numRows;
	private int numCols;
	protected short[][] dataArray = null;
	// private TotalSupportTree newAprioriT = null;
	private String fileName;
	private File filePath;
	private boolean haveDataFlag = true;
	protected BufferedReader fileInput;

	public Database context = new Database();
	public AlgoFPGrowth algo = new AlgoFPGrowth();
	protected Itemsets patterns = new Itemsets("FREQUENT ITEMSETS");
	private double support =40;
	private double minWeight =0.7;
	
	
    // CONSTANTS
    /** Minimum threshold value. */
    final static double MIN_THOLD = 0.0;
    /** Minimum threshold value. */
    final static double MAX_THOLD = 100.0;
    
    private JFrame randomCreateFrame = new JFrame("SpringForm");
    
	public AppControl() {
		getContentPane().setBackground(Color.pink);
		getContentPane().setLayout(new BorderLayout(5, 5)); // 5 pixel gaps

		// Create menus
		createFileMenu();
		createTholdInputMenu();
		createDataPreProcMenu();
		createAlgoMenu();
		// createAprioriTmenu();
		// createGeneratorMenu();
		createOutputMenu();

		// Create menu bar
		JMenuBar bar = new JMenuBar();
		setJMenuBar(bar);
		bar.add(fileMenu);
		bar.add(tHoldInputMenu);
		bar.add(dataPreProcMenu);
		bar.add(algoMenu);
		// bar.add(aprioriTmenu);
		// bar.add(generatorMenu);
		bar.add(outputMenu);

		// Add text area
		textArea = new JTextArea(40, 40);
		textArea.setEditable(false);
		getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER);

		// Credits Panel
		createCreditsPanel();
		getContentPane().add(creditsPanel, BorderLayout.SOUTH);
	};

	private void createFileMenu() {
		// Create file menu
		fileMenu = new JMenu("File");
		fileMenu.setMnemonic('F');

		// Create file menu items
		fileMenuItems = new JMenuItem[fileMenuLabels.length];
		for (int index = 0; index < fileMenuLabels.length; index++) {
			fileMenuItems[index] = new JMenuItem(fileMenuLabels[index]);
			fileMenuItems[index].setEnabled(true);
			fileMenuItems[index].addActionListener(this);
			if (index > 0)
				fileMenu.addSeparator();
			fileMenu.add(fileMenuItems[index]);
		}
	}

	/** Creates parameter input menu */

	private void createTholdInputMenu() {
		// Create file menu
		tHoldInputMenu = new JMenu("Param. Input");
		tHoldInputMenu.setMnemonic('P');

		// Create threshold menu items
		tholdInputMenuItems = new JMenuItem[tHoldInputMenuLabels.length];
		for (int index = 0; index < tHoldInputMenuLabels.length; index++) {
			tholdInputMenuItems[index] = new JMenuItem(
					tHoldInputMenuLabels[index]);
			tholdInputMenuItems[index].setEnabled(true);
			tholdInputMenuItems[index].addActionListener(this);
			if (index > 0)
				tHoldInputMenu.addSeparator();
			tHoldInputMenu.add(tholdInputMenuItems[index]);
		}
	}

	/** Creates data pre-processing menu. */

	private void createDataPreProcMenu() {
		// Create data pre-processing menu
		dataPreProcMenu = new JMenu("Data Pre-proc.");
		dataPreProcMenu.setMnemonic('D');

		// Create data pre-processing menu items
		dataPreProcMenuItems = new JMenuItem[dataPreProcMenuLabels.length];
		for (int index = 0; index < dataPreProcMenuLabels.length; index++) {
			dataPreProcMenuItems[index] = new JMenuItem(
					dataPreProcMenuLabels[index]);
			dataPreProcMenuItems[index].setEnabled(true);
			dataPreProcMenuItems[index].addActionListener(this);
			if (index > 0)
				dataPreProcMenu.addSeparator();
			dataPreProcMenu.add(dataPreProcMenuItems[index]);
		}
	}

	/** Creates algorithm menu. */

	private void createAlgoMenu() {
		// Create algorithm menu
		algoMenu = new JMenu("Algorithms");
		algoMenu.setMnemonic('L');

		// Create algorithm menu items
		algoMenuItems = new JMenuItem[algoMenuLabels.length];
		for (int index = 0; index < algoMenuLabels.length; index++) {
			algoMenuItems[index] = new JMenuItem(algoMenuLabels[index]);
			algoMenuItems[index].setEnabled(true);
			algoMenuItems[index].addActionListener(this);
			if (index > 0)
				algoMenu.addSeparator();
			algoMenu.add(algoMenuItems[index]);
		}
	}

	/** Creates Aprior-T ARM menu. */
	/*
	 * private void createAprioriTmenu() { // Create data pre-processing menu
	 * aprioriTmenu = new JMenu("Apriori-T"); aprioriTmenu.setMnemonic('A');
	 * 
	 * // Create Apriori-T menu items aprioriTmenuItems = new
	 * JMenuItem[aprioriTmenuLabels.length]; for (int
	 * index=0;index<aprioriTmenuLabels.length;index++) {
	 * aprioriTmenuItems[index] = new JMenuItem(aprioriTmenuLabels[index]);
	 * aprioriTmenuItems[index].setEnabled(true);
	 * aprioriTmenuItems[index].addActionListener(this); if (index>0)
	 * aprioriTmenu.addSeparator(); aprioriTmenu.add(aprioriTmenuItems[index]);
	 * }
	 * 
	 * // Add DIC sub-menu aprioriTmenu.addSeparator();
	 * createAprioriT_DICmenu(); aprioriT_DICmenu.setEnabled(true);
	 * aprioriTmenu.add(aprioriT_DICmenu);
	 * 
	 * // Add negative boarder sub-menu aprioriTmenu.addSeparator();
	 * createAprioriTnegBoardMenu(); aprioriTnegBoardMenu.setEnabled(true);
	 * aprioriTmenu.add(aprioriTnegBoardMenu); }
	 */
	/** Creates Aprior-T DIC menu. */

	/*
	 * private void createAprioriT_DICmenu() { // Create AprioriT DIC menu
	 * aprioriT_DICmenu = new JMenu("Apriori-T DIC");
	 * aprioriT_DICmenu.setMnemonic('D');
	 * 
	 * // Create AprioriT DIC menu items aprioriT_DICmenuItems = new
	 * JMenuItem[aprioriT_DICmenuLabels.length]; for (int
	 * index=0;index<aprioriT_DICmenuLabels.length;index++) {
	 * aprioriT_DICmenuItems[index] = new
	 * JMenuItem(aprioriT_DICmenuLabels[index]);
	 * aprioriT_DICmenuItems[index].setEnabled(true);
	 * aprioriT_DICmenuItems[index].addActionListener(this); if (index>0)
	 * aprioriT_DICmenu.addSeparator();
	 * aprioriT_DICmenu.add(aprioriT_DICmenuItems[index]); } }
	 */
	/** Creates Aprior-T Negative Boarder ARM menu. */
	/*
	 * private void createAprioriTnegBoardMenu() { // Create Apriori-T Negative
	 * Boarder ARM menu aprioriTnegBoardMenu = new
	 * JMenu("Apriori-T Neg. Board."); aprioriTnegBoardMenu.setMnemonic('N');
	 * 
	 * // Create Apriori-T Negative Boarder menu items aprioriTnegBoardMenuItems
	 * = new JMenuItem[aprioriTnegBoardMenuLabels.length]; for (int
	 * index=0;index<aprioriTnegBoardMenuLabels.length;index++) {
	 * aprioriTnegBoardMenuItems[index] = new
	 * JMenuItem(aprioriTnegBoardMenuLabels[index]);
	 * aprioriTnegBoardMenuItems[index].setEnabled(true);
	 * aprioriTnegBoardMenuItems[index].addActionListener(this); if (index>0)
	 * aprioriTnegBoardMenu.addSeparator();
	 * aprioriTnegBoardMenu.add(aprioriTnegBoardMenuItems[index]); } }
	 */
	/** Creates generator menu */

	/*
	 * private void createGeneratorMenu() { // Create generator menu
	 * generatorMenu = new JMenu("Generator"); generatorMenu.setMnemonic('G');
	 * 
	 * // Create generator menu items generatorMenuItems = new
	 * JMenuItem[generatorMenuLabels.length]; for (int
	 * index=0;index<generatorMenuLabels.length;index++) {
	 * generatorMenuItems[index] = new JMenuItem(generatorMenuLabels[index]);
	 * generatorMenuItems[index].setEnabled(true);
	 * generatorMenuItems[index].addActionListener(this); if (index>0)
	 * generatorMenu.addSeparator();
	 * generatorMenu.add(generatorMenuItems[index]); } }
	 */
	/** Creates output menu */

	private void createOutputMenu() {
		// Create output menu
		outputMenu = new JMenu("Output");
		outputMenu.setMnemonic('O');

		// Define array of output menu items.
		outputMenuItems = new JMenuItem[outputMenuLables.length];

		// Create output menu items
		outputMenuItems = new JMenuItem[outputMenuLables.length];
		for (int index = 0; index < outputMenuLables.length; index++) {
			outputMenuItems[index] = new JMenuItem(outputMenuLables[index]);
			outputMenuItems[index].setEnabled(true);
			outputMenuItems[index].addActionListener(this);
			if (index > 0)
				outputMenu.addSeparator();
			outputMenu.add(outputMenuItems[index]);
		}
		outputMenu.addSeparator();

		// Create output data array sub-menu items
		createDataArrayOutputMenu();
		dataArrayOutputMenu.setEnabled(true);
		outputMenu.add(dataArrayOutputMenu);
		outputMenu.addSeparator();

		// Create output T-tree sub-menu items
		/*
		 * createTtreeOutputMenu(); tTreeOutputMenu.setEnabled(true);
		 * outputMenu.add(tTreeOutputMenu); outputMenu.addSeparator();
		 */
		// Create output DIC T-tree sub-menu items
		/*
		 * createDIC_TtreeOutputMenu(); dicTtreeOutputMenu.setEnabled(true);
		 * outputMenu.add(dicTtreeOutputMenu); outputMenu.addSeparator();
		 */
		// Create output frequent sets sub-menu items
		createFreqSetsOutputMenu();
		freqSetOutputMenu.setEnabled(true);
		outputMenu.add(freqSetOutputMenu);
		outputMenu.addSeparator();

		// Create output association rules sub-menu items
		createARsOutputMenu();
		assocRuleOutputMenu.setEnabled(true);
		outputMenu.add(assocRuleOutputMenu);
		outputMenu.addSeparator();

		// Create output diagnistics sub-menu items
		createdDagnosticOutputSubMenu();
		diagnosticOutputSubMenu.setEnabled(true);
		outputMenu.add(diagnosticOutputSubMenu);
	}

	/** Creates data array output sub-menu */

	private void createDataArrayOutputMenu() {
		// Create data array output menu
		dataArrayOutputMenu = new JMenu("Data Array");
		dataArrayOutputMenu.setMnemonic('D');

		// Create buttons
		dataArrayOutputMenuItems = new JMenuItem[outputDataArrayMenuLabels.length];
		for (int index = 0; index < outputDataArrayMenuLabels.length; index++) {
			dataArrayOutputMenuItems[index] = new JMenuItem(
					outputDataArrayMenuLabels[index]);
			dataArrayOutputMenuItems[index].setEnabled(true);
			dataArrayOutputMenuItems[index].addActionListener(this);
			if (index > 0)
				dataArrayOutputMenu.addSeparator();
			dataArrayOutputMenu.add(dataArrayOutputMenuItems[index]);
		}
	}

	/** Creates T-tree output sub-menu */

	/*
	 * private void createTtreeOutputMenu() { // Create T-tree output menu
	 * tTreeOutputMenu = new JMenu("T-Tree"); tTreeOutputMenu.setMnemonic('T');
	 * 
	 * // Create buttons tTreeOutputMenuItems = new
	 * JMenuItem[outputTtreeMenuLabels.length]; for (int
	 * index=0;index<outputTtreeMenuLabels.length;index++) {
	 * tTreeOutputMenuItems[index] = new
	 * JMenuItem(outputTtreeMenuLabels[index]);
	 * tTreeOutputMenuItems[index].setEnabled(true);
	 * tTreeOutputMenuItems[index].addActionListener(this); if (index>0)
	 * tTreeOutputMenu.addSeparator();
	 * tTreeOutputMenu.add(tTreeOutputMenuItems[index]); } }
	 */
	/** Creates DIC T-tree output sub-menu */
	/*
	 * private void createDIC_TtreeOutputMenu() { // Create T-tree output menu
	 * dicTtreeOutputMenu = new JMenu("DIC T-Tree");
	 * dicTtreeOutputMenu.setMnemonic('D');
	 * 
	 * // Create buttons dicTtreeOutputMenuItems = new
	 * JMenuItem[outputDIC_TtreeMenuLabels.length]; for (int
	 * index=0;index<outputDIC_TtreeMenuLabels.length;index++) {
	 * dicTtreeOutputMenuItems[index] = new
	 * JMenuItem(outputDIC_TtreeMenuLabels[index]);
	 * dicTtreeOutputMenuItems[index].setEnabled(true);
	 * dicTtreeOutputMenuItems[index].addActionListener(this); if (index>0)
	 * dicTtreeOutputMenu.addSeparator();
	 * dicTtreeOutputMenu.add(dicTtreeOutputMenuItems[index]); } }
	 */
	/** Creates frequent sets output sub-menu */

	private void createFreqSetsOutputMenu() {
		// Create output frequent sets menu
		freqSetOutputMenu = new JMenu("Frequent Sets");
		freqSetOutputMenu.setMnemonic('S');

		// Create buttons
		freqSetOutputMenuItems = new JMenuItem[outputFreqSetsMenuLabels.length];
		for (int index = 0; index < outputFreqSetsMenuLabels.length; index++) {
			freqSetOutputMenuItems[index] = new JMenuItem(
					outputFreqSetsMenuLabels[index]);
			freqSetOutputMenuItems[index].setEnabled(true);
			freqSetOutputMenuItems[index].addActionListener(this);
			if (index > 0)
				freqSetOutputMenu.addSeparator();
			freqSetOutputMenu.add(freqSetOutputMenuItems[index]);
		}
	}

	/** Creates association rules output sub-menu */

	private void createARsOutputMenu() {
		// Create output association rules menu
		assocRuleOutputMenu = new JMenu("Association Rules");
		assocRuleOutputMenu.setMnemonic('A');

		// Create buttons
		assocRuleOutputMenuItems = new JMenuItem[outputAssocRulesMenuLabels.length];
		for (int index = 0; index < outputAssocRulesMenuLabels.length; index++) {
			assocRuleOutputMenuItems[index] = new JMenuItem(
					outputAssocRulesMenuLabels[index]);
			assocRuleOutputMenuItems[index].setEnabled(true);
			assocRuleOutputMenuItems[index].addActionListener(this);
			if (index > 0)
				assocRuleOutputMenu.addSeparator();
			assocRuleOutputMenu.add(assocRuleOutputMenuItems[index]);
		}
	}

	/** Creates association rules output sub-menu */

	private void createdDagnosticOutputSubMenu() {
		// Create diagnostic output menu
		diagnosticOutputSubMenu = new JMenu("Diagnostics");
		diagnosticOutputSubMenu.setMnemonic('D');

		// Create buttons
		diagnosticOutputMenuItems = new JMenuItem[outputDiagnosticMenuLabels.length];
		for (int index = 0; index < outputDiagnosticMenuLabels.length; index++) {
			diagnosticOutputMenuItems[index] = new JMenuItem(
					outputDiagnosticMenuLabels[index]);
			diagnosticOutputMenuItems[index].setEnabled(true);
			diagnosticOutputMenuItems[index].addActionListener(this);
			if (index > 0)
				diagnosticOutputSubMenu.addSeparator();
			diagnosticOutputSubMenu.add(diagnosticOutputMenuItems[index]);
		}
	}

	/* --------------------------------- */
	/*                                   */
	/* CREATE CREDITS PANELS */
	/*                                   */
	/* --------------------------------- */

	/** Creates credits panel. */

	private void createCreditsPanel() {
		// Swet up panel
		creditsPanel = new JPanel();
		creditsPanel.setBackground(Color.pink);
		creditsPanel.setLayout(new GridLayout(4, 1));

		// Create labels
		Label creditLabel1 = new Label(
				"Phòng Công nghệ phần mềm trong Quản lý "
						+ "Viện Công nghệ thông tin");
		Label creditLabel2 = new Label(
				"Minh họa các thuật toán khai phá dữ liệu ");
		Label creditLabel3 = new Label("---------");
		Label creditLabel4 = new Label("Phiên bản 1 - " + "(Tháng 3 năm 2012)");
		// Add labels
		creditsPanel.add(creditLabel1);
		creditsPanel.add(creditLabel2);
		creditsPanel.add(creditLabel3);
		creditsPanel.add(creditLabel4);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		// File menu item About
		if (event.getActionCommand().equals("About")) {
			textArea.append("VỀ PHẦN MỀM :\n");
			aboutSoftware();
			textArea.append("-------------------------------------\n");
		}

		// File menu load data
		else if (event.getActionCommand().equals("Load Data")) {
			textArea.append("Tên file dữ liệu:\n");
			try {
				loadData();
			} catch (FileNotFoundException a) {
			}
			textArea.append("-------------------------------------\n");
		}

		// File menu load output schema
		else if (event.getActionCommand().equals("Load Weight")) {
			textArea.append("Tên file trọng số:\n");
			try{
				loadOutputSchema();
		    } catch (FileNotFoundException a){
			}
			 
			textArea.append("-------------------------------------\n");
		}
		else if (event.getActionCommand().equals("Randomize Weight")) {
			textArea.append("Tạo mảng trọng số ngẫu nhiên:\n");
			createRandomWeight();
			textArea.append("-------------------------------------\n");
		}
		// File menu exit
		else if (event.getActionCommand().equals("Exit")) {
			System.exit(0);
		}

		// Threshold input menu item add support threshold
		else if (event.getActionCommand().equals("Support")) {
			textArea.append("Ngưỡng hỗ trợ:\n");
			inputSupportThold();
			textArea.append("-------------------------------------\n");
		}
		else if (event.getActionCommand().equals("Min Weight")) {
			textArea.append("Trọng số nhỏ nhất:\n");
			inputMinWeight();
			textArea.append("-------------------------------------\n");
		}

		// Threshold input menu item add confidence threshold
		else if (event.getActionCommand().equals("Confidence")) {
			textArea.append("INPUT CONFIDENCE THRESHOLDS:\n");
			// inputConfidenceThold();
			textArea.append("-------------------------------------\n");
		}

		// Data pre-processing menu item sort input data. */
		else if (event.getActionCommand().equals("Sort")) {
			textArea.append("SORT INPUT DATA:\n");
			// sortInputData();
			textArea.append("-------------------------------------\n");
		}

		// Data pre-processing menu item sort and prune input data. */
		else if (event.getActionCommand().equals("Sort & Prune")) {
			textArea.append("SORT AND PRUNE INPUT DATA:\n");
			// sortAndPruneInputData();
			textArea.append("-------------------------------------\n");
		}
		
		// Apriori-T menu item apriori-T without X checking. */
		else if (event.getActionCommand().equals("Apriori T (with X check)")) {
			textArea.append("APRIORI-T (WITH X CHECK):\n");
			// aprioriTwithXcheck();
			textArea.append("-------------------------------------\n");
		}
		//WFIM algorithm
		else if (event.getActionCommand().equals("WFIM (Weighted frequent itemset mining)")) {
			textArea.append("WFIM (Weighted frequent itemset mining):\n");
			//support in double
			double minsupp = support/100;
			patterns = algo.runAlgorithm(context, minsupp, minWeight);
			printStart();
			textArea.append("-------------------------------------\n");
		}
		
		// Apriori-T menu item apriori-T with X checking. */
		else if (event.getActionCommand().equals("Apriori T (without X check)")) {
			textArea.append("APRIORI-T (WITH OUT X CHECK):\n");
			// aprioriTnoXcheck();
			textArea.append("-------------------------------------\n");
		}

		// Apriori-T menu item DIC algorithm. */
		else if (event.getActionCommand().equals("Apriori T DIC")) {
			textArea.append("APRIORI-T WITH DYNAMIC ITEMSET COUNTING:\n");
			// aprioriTdic();
			textArea.append("-------------------------------------\n");
		}

		// Apriori-T menu item apriori-T DIC set block size. */
		else if (event.getActionCommand().equals("Set DIC Block Size")) {
			textArea.append("SET APRIORI-T WITH DIC BLOCK SIZE:\n");
			// setDICblockSize();
			textArea.append("-------------------------------------\n");
		}

		// Apriori-T menu item negatove boarder algorithm. */
		else if (event.getActionCommand().equals("Apriori T Neg. Boarder")) {
			textArea.append("APRIORI-T NEGATIVE BOARDER (WITH X CHECK):\n");
			// aprioriTnegBoarder();
			textArea.append("-------------------------------------\n");
		}

		// Apriori-T menu item set negative boarder reduction value. */
		else if (event.getActionCommand().equals("Set reduction value")) {
			textArea.append("SET APRIORI-T NEGATIVE BOARDER SUPPORT REDUCTION:\n");
			// setSupportReduction();
			textArea.append("-------------------------------------\n");
		}

		// Generate menu item generate ARs with min. confidence framework.
		else if (event.getActionCommand().equals("Generate ARs (Min Conf)")) {
			textArea.append("GENERATE ARs (SUPPORT AND CONFIDENCE FRAMEWORK):\n");
			// generateARsMinConf();
			textArea.append("-------------------------------------\n");
		}

		// Generate menu item generate ARs with lift framework.
		else if (event.getActionCommand().equals("Generate ARs (Lift)")) {
			textArea.append("GENERATE ARs (SUPPORT AND LIFT FRAMEWORK):\n");
			// generateARsLift();
			textArea.append("-------------------------------------\n");
		}

		// Output schema output sub-memu item output using attribute numbers
		else if (event.getActionCommand().equals("Output Schema")) {
			textArea.append("OUTPUT OUTPUT SCHEMA CONTENTS:\n");
			// outputOutputSchema();
			textArea.append("-------------------------------------\n");
		}

		// Data array output sub-memu item output using attribute numbers
		else if (event.getActionCommand().equals("Data Att. Numbers")) {
			textArea.append("OUTPUT DATA ARRAY USING ATTRIBUTE NUMBERS:\n");
			// outputDataArrayAtts();
			textArea.append("-------------------------------------\n");
		}

		// Frequent sets output sub-memu item output using output schema
		else if (event.getActionCommand().equals("Data Output Schema")) {
			textArea.append("OUTPUT DATA ARRAY USING OUTPUT SCHEMA:\n");
			// outputDataArraySchema();
			textArea.append("-------------------------------------\n");
		}

// Frequent sets output sub-memu item output using output schema
		else if (event.getActionCommand().equals("T-tree Statistics")) {
			textArea.append("OUTPUT T-TREE STATISTICS:\n");
			// outputTtreeStats();
			textArea.append("-------------------------------------\n");
		}

		// Frequent sets output sub-memu item output using output schema
		else if (event.getActionCommand().equals("T-Tree (Att. Numbers)")) {
			textArea.append("OUTPUT T-TREE AS TEXTUAL lIST:\n");
			// outputTtree();
			textArea.append("-------------------------------------\n");
		}

		// Frequent sets output sub-memu item output using output schema
		else if (event.getActionCommand().equals("T-tree (Graph)")) {
			textArea.append("OUTPUT T-TREE AS GRAPH IMAGE:\n");
			// outputTtreeGraph();
			textArea.append("-------------------------------------\n");
		}

		// Frequent sets output sub-memu item output using output schema
		else if (event.getActionCommand().equals("DIC T-tree Stats")) {
			textArea.append("OUTPUT DIC T-TREE STATISTICS:\n");
			// outputDIC_TtreeStats();
			textArea.append("-------------------------------------\n");
		}

		// Frequent sets output sub-memu item output using output schema
		else if (event.getActionCommand().equals("DIC T-Tree (Att. Numbers)")) {
			textArea.append("OUTPUT DIC T-TREE AS TEXTUAL lIST:\n");
			// outputDIC_Ttree();
			textArea.append("-------------------------------------\n");
		}

		// Frequent sets output sub-memu item output using attribute numbers
		else if (event.getActionCommand().equals("FSs Att. Numbers")) {
			textArea.append("OUTPUT FREQUENT SETS USING ATTRIBUTE NUMBERS:\n");
			outputFreqSetsAtts(context.size());
			textArea.append("-------------------------------------\n");
		}

		// Frequent sets output sub-memu item output using output schema
		else if (event.getActionCommand().equals("FSs Output Schema")) {
			textArea.append("OUTPUT FREQUENT SETS USING OUTPUT SCHEMA:\n");
			// outputFreqSetsSchema();
			textArea.append("-------------------------------------\n");
		}

		// Association rules output sub-memu item output using attribute numbers
		else if (event.getActionCommand().equals("ARs Att. Numbers")) {
			textArea.append("OUTPUT ASSOCIATION RULES USING ATTRIBUTE NUMBERS:\n");
			// outputARsAtts();
			textArea.append("-------------------------------------\n");
		}

		// Association rules output sub-memu item output using output schema
		else if (event.getActionCommand().equals("ARs Output Schema")) {
			textArea.append("OUTPUT ASSOCIATION RULES USING OUTPUT SCHEMA:\n");
			// outputARsSchema();
			textArea.append("-------------------------------------\n");
		}

		// Diagnostic output sub-memu item output concersion arrays
		else if (event.getActionCommand().equals("Conversion arrays")) {
			textArea.append("OUTPUT CONVERSION AND RECONVERSION ARRAYS:\n");
			// outputConversionArrays();
			textArea.append("-------------------------------------\n");
		}

		// Default
		else {
			JOptionPane.showMessageDialog(null, "ERROR:\n Unrecognised "
					+ "action event,  " + event.getActionCommand() + "\n");
		}
	}
	
	private void createRandomWeight() {
	        //Create and populate the panel.
			
	        final JPanel p = new JPanel(new SpringLayout());
	        
	            JLabel minLabel = new JLabel("Min Weight", SwingConstants.TRAILING);
	            p.add(minLabel);
	            final JTextField minTextField = new JTextField(10);
	            minLabel.setLabelFor(minTextField);
	            p.add(minTextField);
	            
	            JLabel maxLabel = new JLabel("Max Weight", SwingConstants.TRAILING);
	            p.add(maxLabel);
	            final JTextField maxTextField = new JTextField(10);
	            maxLabel.setLabelFor(maxTextField);
	            p.add(maxTextField);
	            
	        JButton okButton = new JButton("OK");
	        okButton.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					try{
						if(context.mapSupport.isEmpty()){
							textArea.append("Phải nạp dữ liệu trước (load data)! \n");
							return;
						}
						int randomMin = Integer.parseInt(minTextField.getText());
						int randomMax = Integer.parseInt(maxTextField.getText());
						if (randomMin >randomMax){
							textArea.append("Min Weight không được lớn hơn Max Weight!\n");
						}
						System.out.println(randomMin + "       "+randomMax);
						context.createRandomWeightRange(randomMin, randomMax);
					}catch (NumberFormatException nfe){
						textArea.append("Dữ liệu không hợp lệ. Xin xem lại!\n");
						//nfe.printStackTrace();
				} finally {
					randomCreateFrame.dispose();
				}							
					
				}
			});
			JButton cancelButton = new JButton("Cancel");

			cancelButton.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					System.out.println("Cancel button was clicked!");
					randomCreateFrame.dispose();
				}
			});
	        p.add(okButton);
	        p.add(cancelButton);
	        //Lay out the panel.
	        SpringUtilities.makeCompactGrid(p,
	                                        3, 2, //rows, cols
	                                        6, 6,        //initX, initY
	                                        6, 6);       //xPad, yPad
	        
	        //Create and set up the window.
	        
	        randomCreateFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	 
	        //Set up the content pane.
	        p.setOpaque(true);  //content panes must be opaque
	        randomCreateFrame.setContentPane(p);
	 
	        //Display the window.
	        randomCreateFrame.pack();
	        //frame.setSize(280, 180);
	        randomCreateFrame.setVisible(true);
	}

	private void outputFreqSetsAtts(int nbObject) {
		// TODO Auto-generated method stub
		textArea.append(" ------- " + patterns.getName() + " -------\n");
		int patternCount=0;
		int levelCount=0;
		for(List<Itemset> level : patterns.getLevels()){
			textArea.append("  L" + levelCount + " \n");
			for(Itemset itemset : level){
				textArea.append("  pattern " + patternCount + ":  ");
				printItem(itemset.getItems());
				textArea.append("support :  " + itemset.getSupportRelatifFormatted(nbObject));
				patternCount++;
				textArea.append(" (" + itemset.getAbsoluteSupport() + "/" + nbObject + ") ");

				textArea.append("\n");
			}
			levelCount++;
		}
		System.out.println(" --------------------------------");
	}

	private String printItem(List<Integer> items) {
		StringBuffer r = new StringBuffer ();
		for(Integer attribute : items){
			r.append(attribute.toString());
			r.append(' ');
		}
		return r.toString();
	}

	private void printStart() {
		textArea.append("=============  FP-GROWTH - STATS =============\n");
		long temps = algo.getEndTime() - algo.getStartTimestamp();
		textArea.append(" Transactions count from database : " + algo.getContextSize()+"\n");
		textArea.append(" Frequent itemsets count : "
				+ algo.getFrequentItemsets().getItemsetsCount()+"\n");
		textArea.append(" Total time ~ " + temps + " ms\n");
		textArea.append("===================================================\n");
	}

	private void inputSupportThold() {
		 String stNum = null;
	        // Try catch block
	        try{
	            while (true) {
	                stNum = JOptionPane.showInputDialog("Nhập tham số ngưỡng hỗ trợ " +
		       		               "(%)\n\n" );
		        // Check if operation cancelled
	                if (stNum == null) {
	                    textArea.append("Tiến trình bị hủy!\n");
	                    break;
	                    }
	                // Process input
	                double newSupportThold = Double.parseDouble(stNum);
	                // Check if within range
	                if ((newSupportThold < MIN_THOLD) ||
	                                               (newSupportThold > MAX_THOLD)) {
			    JOptionPane.showMessageDialog(null,"Lỗi dữ liệu:\n " +
				       "support threshold input,  " + newSupportThold +
	                                  ",\nnot within range " + MIN_THOLD + " to " +
	                                                            MAX_THOLD + ".\n");
	                    textArea.append("Try again!\n");
	                    }
		        else {
	                 support = newSupportThold;
	                 textArea.append("Support threshold is :" +support+"%\n");
	                 break;
		            }
			}
		    }
	        catch(NumberFormatException e) {
			    JOptionPane.showMessageDialog(null,"Lỗi dữ liệu nhập:\n " +
					"Dữ liệu nhập không phải số, support\nthreshold (%) " +
		                        " =  \"" + stNum + "\".\n");
		            textArea.append("Operation failed!\n");
			    }
	}
	private void inputMinWeight() {
		 String stNum = null;
	        // Try catch block
	        try{
	            while (true) {
	                stNum = JOptionPane.showInputDialog("Nhập tham số " +
		       		               "trọng số nhỏ nhất \n\n" );
		        // Check if operation cancelled
	                if (stNum == null) {
	                    textArea.append("Tiến trình bị hủy!\n");
	                    break;
	                    }
	                // Process input
	                double newSupportThold = Double.parseDouble(stNum);
	                // Check if within range
	                minWeight = newSupportThold;
	                textArea.append("Trọng số nhỏ nhất :" +minWeight+"\n");
	                break;
		            }
		    }
	        catch(NumberFormatException e) {
		    JOptionPane.showMessageDialog(null,"Lỗi dữ liệu nhập:\n " +
				"Dữ liệu nhập không phải số, minWeight " +
	                        " =  \"" + stNum + "\".\n");
	            textArea.append("Operation failed!\n");
		    }
	}
	private void loadOutputSchema() throws FileNotFoundException{
		
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int result = fileChooser.showOpenDialog(this);

		// If cancel button selected return
		if (result == JFileChooser.CANCEL_OPTION) {
			textArea.append("Operation cancelled\n");
			return;
		}

		// Obtain selected file
		File inputFileName = fileChooser.getSelectedFile();
		//context = new Database();

		// Read file if readabale (i.e not a direcrory etc.).
		if (checkFileName(inputFileName)) {
			textArea.append("Tên file dữ liệu = " + inputFileName + "\n");
			try {
				// inputDataSet(textArea, inputFileName);
				context.loadWeightFile(inputFileName.getPath());
			} catch (IOException e) {
				JOptionPane.showMessageDialog(null, "Có lỗi xảy ra trong quá trình đọc "
						+ "file: " + inputFileName + "\n", "FILE INPUT ERROR",
						JOptionPane.ERROR_MESSAGE);
			}
			
		}
	}

	private void aboutSoftware() {
		
		textArea.append("Phần mềm minh họa các thuật toán khai phá dữ liệu\n");
		textArea.append("Phiên bản 1.0\n");
		textArea.append("(c) Bản quyền thuộc về Phòng CNPM trong quản lý - Viện CNTT\n");
	}

	private void loadData() throws FileNotFoundException {

		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int result = fileChooser.showOpenDialog(this);

		// If cancel button selected return
		if (result == JFileChooser.CANCEL_OPTION) {
			textArea.append("Tiến trình bị hủy\n");
			return;
		}

		// Obtain selected file
		File inputFileName = fileChooser.getSelectedFile();
		//context = new Database();

		// Read file if readabale (i.e not a direcrory etc.).
		if (checkFileName(inputFileName)) {
			textArea.append("Tên File dữ liệu = " + inputFileName + "\n");
			try {
				// inputDataSet(textArea, inputFileName);
				context.loadFile(inputFileName.getPath());
			} catch (IOException e) {
				JOptionPane.showMessageDialog(null, "Có lỗi xảy ra trong quá trình đọc "
						+ "file: " + inputFileName + "\n", "FILE INPUT ERROR",
						JOptionPane.ERROR_MESSAGE);
				System.exit(1);
			}
		}
	}

	private boolean checkFileName(File fileName) {
		boolean fileOK = true;

		// Check if file name exist
		if (fileName.exists()) {
			// Check if file name is readable
			if (fileName.canRead()) {
				// Check id file name is actually a file
				if (fileName.isFile())
					return (fileOK);
				else
					JOptionPane.showMessageDialog(null,
							"Lỗi đọc file: file là thư mục");
			} else
				JOptionPane
						.showMessageDialog(null, "Lỗi đọc file: Truy cập bị từ chối");
		} else
			JOptionPane.showMessageDialog(null, "Lỗi đọc file: File không tồn tại!");
		// Return

		return (!fileOK);
	}

	private void inputDataSet(JTextArea textArea, File fName)
			throws IOException {
		// Set filePath instance field
		int counter = 0;
		filePath = fName;
		try {
			// Open file
			FileReader file = new FileReader(filePath);
			fileInput = new BufferedReader(file);
		} catch (IOException ioException) {
			JOptionPane.showMessageDialog(null, "Lỗi mở file \""
					+ filePath + "\"", "FILE INPUT ERROR",
					JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
		// Read the file
		String line = fileInput.readLine();
		while (line != null) {
			// checkLine(counter+1,line);
			StringTokenizer dataLine = new StringTokenizer(line);
			int numberOfTokens = dataLine.countTokens();
			if (numberOfTokens == 0)
				break;
			counter++;
			if (numCols < numberOfTokens) {
				numCols = numberOfTokens;
			}
			line = fileInput.readLine();
		}
		numRows = counter;

		createDataArray(fName);

		// Check ordering (only if input format is OK)
		// if (inputFormatOkFlag) {
		// if (checkOrdering()) {
		// Output to text area
		textArea.append("Số bản ghi = " + numRows + "\n");
		// countNumCols();
		textArea.append("Số cột = " + numCols + "\n");
		// Set have data flag to true
		// haveDataFlag = true;
		for (int i = 0; i < numRows; i++) {
			for (int j = 0; j < numCols; j++) {
				textArea.append(dataArray[i][j] + " ");
			}
			textArea.append("\n");
		}
	}

	private void createDataArray(File fName) throws IOException {
		filePath = fName;
		try {
			// Open file
			FileReader file = new FileReader(filePath);
			fileInput = new BufferedReader(file);
		} catch (IOException ioException) {
			JOptionPane.showMessageDialog(null, "Error Opening File \""
					+ filePath + "\"", "FILE INPUT ERROR",
					JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
		dataArray = new short[numRows][numCols];
		String line = fileInput.readLine();
		int irows = 0;
		while (line != null) {
			StringTokenizer dataLine = new StringTokenizer(line);
			int numberOfTokens = dataLine.countTokens();
			for (int icols = 0; icols < numberOfTokens; icols++) {
				dataArray[irows][icols] = new Short(dataLine.nextElement()
						.toString());
			}
			irows++;
			line = fileInput.readLine();
		}

	}
}
